import threading
import datetime
import sys
class WriteBuffer:
    messages = []
    lines = {}
    def __init__(self, fp):
        self.fp = fp
    def write(self, record):
        self.fp.write(record)
        tname = threading.currentThread().getName()
        lines = self.lines
        if tname not in lines:
            lines[tname] = ''
        while True:
            ind = record.find('\n')
            if ind == -1:
                lines[tname] += record
                break
            else:
                line = lines[tname] + record[:ind]
                self.messages.append((str(datetime.datetime.now()), threading.currentThread().getName(), line))
                lines[tname] = ''
                record = record[ind+1:]   
        if(len(self.messages) > 1000):
            self.messages = self.messages[:1000]
class LogFile:        
    def __init__(self):
        self.out_buffer = WriteBuffer(sys.stdout)
        self.err_buffer = WriteBuffer(sys.stderr)
        sys.stdout = self.out_buffer
        sys.stderr = self.err_buffer
        pass    
        
    def get_last_messages(self):
        ret = self.out_buffer.messages + self.err_buffer.messages
        self.out_buffer.messages = []
        self.err_buffer.messages = []
        ret.sort(lambda x,y: cmp(x[0], y[0]))
        ret.sort(lambda x,y: cmp(x[1], y[1]))    
        return ret